<?php

function state_list(){
    $data[0]['id']=0;
    $data[0]['name']='关闭';
    $data[1]['id']=1;
    $data[1]['name']='开启';
    return $data;
}

 
 function deldir($dir) {
    //先删除目录下的文件：
    $dh=opendir($dir);
    while ($file=readdir($dh)) {
       if($file!="." && $file!="..") {
          $fullpath=$dir."/".$file;
          if(!is_dir($fullpath)) {
             unlink($fullpath);
          } else {
             deldir($fullpath);
          }
       }
    }
  
    closedir($dh);
    //删除当前文件夹：
    if(rmdir($dir)) {
       return true;
    } else {
       return false;
    }
 }

 

function left_menu($cid){
    $cate=db_find('cate',"pid=".$cid);
    if($cate){
        return true;
    }
     $cate=db_find('cate',"id=".$cid);
     if($cate['pid']>0){
         return true;
     }
     return false;
}

function page_url($str){
	$str=str_replace("?page=","/page_",$str);
	return $str;
}

 function diff_day($day1, $day2)
 {
     $second1 = strtotime($day1);
     $second2 = strtotime($day2);
     if ($second1 < $second2) {
         $tmp = $second2;
         $second2 = $second1;
         $second1 = $tmp;
     }
     $day = (($second1 - $second2) / 86400);
     return $day;
 }

function get_cookie($url){
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    // 获取头部信息 
    curl_setopt($ch, CURLOPT_HEADER, 1); 
    // 返回原生的（Raw）输出 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36');
    // 执行并获取返回结果 
    $content = curl_exec($ch); 
   
    // 关闭CURL 
    curl_close($ch); 
    // 解析HTTP数据流 
    list($header, $body) = explode("\r\n\r\n", $content); 
 
    preg_match("/set\-cookie:([^\r\n]*)/i", $header, $matches); 
   
    $cookie = explode(';',$matches[1])[0] ; 
    
    return $cookie;
}

function create_theme(){
	$str="";
	$css=site_config('site_css');
	if($css){
		$str.="{$css}";	
	}
	if($str){
		file_put_contents(env('root_path').'/template/'.site_config('site_theme').'/__static__'."/img/theme.css",$str);
	}
}


function  temp_list($name){
	$dir= env('root_path').'template'.DIRECTORY_SEPARATOR.site_config('site_theme').DIRECTORY_SEPARATOR ;
	$dir_list=\scandir($dir);
	$data=[];
	foreach ($dir_list as $key=>$value) 
	{ 
		if (is_file($dir.$value) && strpos($value,$name)===0 ) 
		{
			$item=[];
			$item['id']=$value;
			$item['name']=$value;
			$data[]=$item;
		}
	}
	return $data;
}


function  theme_list(){
	$dir= env('root_path').'template'.DIRECTORY_SEPARATOR ;
	$dir_list=\scandir($dir);
	$data=[];
	foreach ($dir_list as $key=>$value) 
	{ 
		if (is_dir($dir.$value) && $value != '.' && $value != '..') 
		{
			$item=[];
			$item['id']=$value;
			$item['name']=$value;
			$data[]=$item;
		}
	}
	return $data;
}

function site_config($name)
{
    try{
           $map['name']=$name;
           return Db::name('config')->where($map)->value('value');
       } catch (Exception $e) {
           return '';
       }
}
function db_name($name, $map, $field='name',$order='id')
{
    if (is_null($map) || $map=='') {
        $map['id']=null;
    }
    return Db::name($name)->where($map)->order($order)->value($field);
}
function db_find($name, $map, $order='id')
{
    return Db::name($name)->where($map)->order($order)->find();
}
function db_list($name, $map, $order='id desc',$limit=10)
{
    return Db::name($name)->where($map)->order($order)->limit($limit)->select();
}

function db_count($name, $map)
{
    return Db::name($name)->where($map)->count();
}

function dict_list($pid)
{
    return Db::name('dict')->where('pid', $pid)->field("value as id,name")->select();
}

function dict_name($value, $pid)
{
    return Db::name('dict')->where('pid', $pid)->where('value', $value)->value('name');
}

function get_category($category_id)
{
    $category_ids[] = $category_id;
    trace($category_id);
    $child_category = db('art_cate')->where('pid', $category_id)->select();
    if (!empty($child_category)) {
        foreach ($child_category as $key => $val) {
            $category_ids = array_merge($category_ids, get_category($val["id"]));
        }
    }
    return $category_ids;
}

 

 function encrypt($str, $key="kpcms")
 {
     $key=sha1($key);
     $data = openssl_encrypt($str, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
     $data = base64_encode($data);
     return $data;
 }

   
   function decrypt($str, $key="kpcms")
   {
       $key=sha1($key);
       $decrypted = openssl_decrypt(base64_decode($str), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
       return $decrypted;
   }


function baidu_push($urls){
	$api = site_config('baidu_push');
	if(empty($api)){
		return false;
	}
	$ch = curl_init();
	$options =  array(
	    CURLOPT_URL => $api,
	    CURLOPT_POST => true,
	    CURLOPT_RETURNTRANSFER => true,
	    CURLOPT_POSTFIELDS => implode("\n", $urls),
	    CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
	);
	curl_setopt_array($ch, $options);
	$result = curl_exec($ch);
	curl_close($ch);
	return json_decode($result,true);
}

function http_post($url, $para = '', $cookie='')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    if (!empty($para)) {
        if (is_array($para)) {
            $para = http_build_query($para);
        }
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $para);
    }
     
    if (strpos($url, 'https://') !== false) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
    if (!empty($cookie)) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400");
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function html_select($name, $value, $option, $first = null)
{
	if(is_null($value)){
		$value='';
	}
    $str = "<select name='{$name}' id='{$name}' class='input'>";
    if (!empty($first)) {
        $str .= "<option value=''>{$first}</option>";
    }
    foreach ($option as $option_vo) {
        $str .= "<option value=\"{$option_vo['id']}\" " . ($value !== '' && $value == $option_vo['id']? "selected" : '') . ">{$option_vo['name']}</option>";
    }
    $str .= "</select>";
    return $str;
}

function html_select2($name,$value,$option,$first=null){
    $option=list_to_tree($option);
    $select_str="<select name='{$name}' class='input' >";
    if(!empty($first)){
        $select_str.="<option value=''>{$first}</option>";
    }
    foreach ($option as $option_one){
        $select_str.="<option  value=\"{$option_one['id']}\" ".($option_one['id']==$value?"selected":'').">{$option_one['name']}</option>";
        if(!empty($option_one['_child'])){
            foreach ($option_one['_child'] as $option_two){
                $select_str.="<option value=\"{$option_two['id']}\" ".($option_two['id']==$value?"selected":'').">　{$option_two['name']}</option>";
                if(!empty($option_two['_child'])){
                    foreach ($option_two['_child'] as $option_three){
                        $select_str.="<option value=\"{$option_three['id']}\" ".($option_three['id']==$value?"selected":'').">　　{$option_three['name']}</option>";
                    }
                }
            }
        }
    }
    $select_str.="</select>";
    return $select_str;
}

function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = &$refer[$parentId];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}

function get_cate_pid($id){
	$arr = array();
	$cate = db('cate')->where('id',$id)->find();
	if(!empty($cate)){
		$arr[]=$cate['id'];
		if($cate['pid'] != '0'){
			$arr = array_merge(get_cate_pid($cate['pid']),$arr);
		}
		return $arr;
	}
}

 

function get_cate_ids($id){
	$arr = array();
	$arr[]=$id;
	$cate_list = db('cate')->where('pid',$id)->select();
	foreach($cate_list as $cate){
		$arr = array_merge(get_cate_ids($cate['id']),$arr);
	}
	return $arr;
}
